package com.nowcoder.community.service;

import com.nowcoder.community.contant.Entity;
import com.nowcoder.community.contant.Topic;
import com.nowcoder.community.entity.Comment;
import com.nowcoder.community.entity.Event;
import com.nowcoder.community.event.EventProducer;
import com.nowcoder.community.repository.CommentMapper;
import com.nowcoder.community.repository.DiscussPostMapper;
import com.nowcoder.community.utils.SensitiveWordFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.util.HtmlUtils;

import java.util.Date;
import java.util.List;

@Service
public class CommentService {
    @Autowired
    private CommentMapper commentMapper;

    @Autowired
    private DiscussPostMapper discussPostMapper;

    @Autowired
    private SensitiveWordFilter sensitiveWordFilter;

    @Autowired
    private EventProducer eventProducer;

    public List<Comment> findCommentsByEntity(int entityType, int entityId, int offset, int limit){
        return commentMapper.selectCommentsByEntity(entityType, entityId, offset, limit);
    }

    // 用户评论
    public List<Comment> findCommentsByUserId(int userId, int entityType, int offset, int limit){
        return commentMapper.selectCommentsByUserId(userId, entityType, offset, limit);
    }

    public int countCommentsByEntity(int entityType, int entityId){
        return commentMapper.countCommentsByEntity(entityType, entityId);
    }

    public int countCommentsByUserId(int userId, int entityType){
        return commentMapper.countCommentsByUserId(userId, entityType);
    }

    @Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED)
    public Comment addComment(Comment comment){
        // 添加评论
        comment.setContent(sensitiveWordFilter.filter(HtmlUtils.htmlEscape(comment.getContent())));
        comment.setCreateTime(new Date());
        comment.setStatus(0);
        commentMapper.insertComment(comment);

        // 更新帖子评论数量
        if (comment.getEntityType() == Entity.DISCUSS_POST){
            discussPostMapper.updateCommentCount(comment.getEntityId(), commentMapper.countCommentsByEntity(comment.getEntityType(), comment.getEntityId()));
            // 更新 es
            Event event = new Event()
                    .setTopic(Topic.POST_PUBLISH)
                    .setEntityType(comment.getEntityType())
                    .setEntityId(comment.getEntityId());
            eventProducer.fireEvent(event);
        }

        return comment;
    }
}
